import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from './User.entity';

@Injectable()
export class UserService {

  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>
  ) { }

  async findOne(userId: string): Promise<UserEntity> {
    const user = await this.userRepository.findOne({
      where: {
        id: userId,
      },
    });
    if (!user) {
      throw new Error('user not found');
    }
    return user;
  }

  
  async findOneByName(userName: string): Promise<UserEntity> {
    const user = await this.userRepository.findOne({
      where: {
        userName,
      },
    });
    if (!user) {
      throw new Error('user not found -- findOneByName');
    }
    return user;
  }

  
  async findAll(): Promise<UserEntity[]> {
    const users = await this.userRepository.find();
    return users;
  }


  
  // 添加回复
  async addAUser(userDto: any): Promise<any> {
    const { userName,wxID,userPassword } = userDto;
    const u = await this.userRepository.findOne({ 
      where: {
        userName,
      },
     });
    if (u) {
      return {
        errorCode:1,
        errorInfo:"oh,no!"
      };
    }

    return await this.userRepository.save({
      wxID,
      userName,
      userPassword,
      isActive:false
    });
  }


  async deleteUserByID(userID: string): Promise<any> {
    return await this.userRepository.delete({ id: userID });
  }

}
